//
//  SinaOAuthViewController.swift
//  SinaWeibo
//
//  Created by 王朝阳 on 2016/10/24.
//  Copyright © 2016年 wangzhaoyang. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD

class SinaOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    //MARK: - 点击事件
    //取消
    @objc private func cancleClick() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    //自动填充
    @objc private func autoFillClick() {
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(SinaWeName)',document.getElementById('passwd').value='\(SinaWePsswd)'"
        //js 注入
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    //MARK: - 设置视图
    private func setupUI() {
        view.backgroundColor = UIColor.white
        setupNav()
    }
    
    //MARK: - 设置导航条
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(setHighlightedImgName: nil, title: "取消", target: self, action: #selector(cancleClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(setHighlightedImgName: nil, title: "自动填充", target: self, action: #selector(autoFillClick))
        navigationItem.title = "微博登录"
    }
    //MARK: - 创建 WebView
    private lazy var webView: UIWebView = {
       
        //url
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(SinaAppKey)&redirect_uri=\(SinaRedirectURI)")!
//        print(url)
        let request = URLRequest(url: url)
        let view = UIWebView()
        view.delegate = self
        view.loadRequest(request)
        return view
    }()
   
}
//MARK: - UIWebViewDelegate
extension SinaOAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //urlString
        let urlString = request.url?.absoluteString
        //判断 urlString是否为 nil, 是否包含回调页
        
        if let u = urlString,u.hasPrefix(SinaRedirectURI) {
            //请求参数
            let qury = request.url?.query
            //判断请求参数是否为空
            if let q = qury {
                //截取出 code = b447ca46dc68b423cb631f5365affe6c
                let code = q.substring(from: "code=".endIndex)
                print(code)
//                getUserAccount(code: code)
//                SinaUserAccountViewModel.sharedTools.getUserAccount(code: code)
                SinaUserAccountViewModel.sharedTools.getUserAccount(code: code, finish: { (isSuccess) in
                    if !isSuccess {
                        print("请求失败")
                        SVProgressHUD.showError(withStatus: "请求失败")
                        return
                    }
                    print("请求成功")
                    SVProgressHUD.dismiss()
                    //让回调页界面消失之后跳转到欢迎界面
                     self.dismiss(animated: false, completion: { 
                        //发送通知跳转到欢迎界面
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: SinaSwitchRootVCNoti), object: nil)
                     })
                })
            }
            //不加载授权界面
            return false
        }
        return true
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
         SVProgressHUD.showError(withStatus: "请求失败")
    }
}






